﻿using System;

#if SILVERLIGHT
namespace SBPweb.RIA.Client.Common.Patterns
#else
namespace SBPweb.RIA.Server.Common.Patterns
#endif
{

    public class SingletonHelper<T>
    {

        #region Private fields

        private MulticastDelegate creator;

        private object sync = new object();

        private T instance;

        #endregion

        #region Constructor logic

        public SingletonHelper()
        {
        }

        public SingletonHelper(MulticastDelegate creator)
        {
            this.creator = creator;
        }

        #endregion

        #region Property accessors

        public T Instance
        {
            get
            {
                lock (sync)
                {
                    if (!object.Equals(instance, default(T)))
                    {
                        return instance;
                    }
                    instance = Create();
                    if (InstanceCreated != null)
                    {
                        InstanceCreated(this, EventArgs.Empty);
                    }
                    return instance;
                }
            }
        }

        #endregion

        #region Events

        public static event EventHandler InstanceCreated;

        #endregion

        #region Methods

        private T Create()
        {
            if (creator != null)
            {
                return (T)creator.DynamicInvoke();
            }
            return Activator.CreateInstance<T>();
        }

        #endregion

    }

}